<template>
  <div class="">
    <a-spin :loading="spinLoading" :tip="spinTip" dot style="width: 100%;">
      <a-card class="custom-card">
        <div ref="searchRef">
          <a-row v-if="showSearch" class="table-search mb-3">
            <a-col :flex="1">
              <a-form
                :model="query"
                layout="inline"
                label-align="left"
              >
                <a-row :gutter="8">
                  <a-col flex="260px">
                    <a-input-group>
                      <a-select v-model="query.keyword_type" placeholder="请选择" :style="{width:'120px'}">
                        <a-option value="name">名称</a-option>
                      </a-select>
                      <a-input v-model="query.name" placeholder="请输入名称" allow-clear />
                    </a-input-group>
                  </a-col>
                  <a-col flex="200px">
                    <a-form-item label="类型" field="">
                      <a-select v-model="query.type" placeholder="" allow-clear>
                        <a-option value="1" label="类型1" />
                        <a-option value="2" label="类型2" />
                        <a-option value="3" label="类型3" />
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col flex="200px">
                    <a-form-item label="状态" field="">
                      <a-select v-model="query.status" :options="statusOptions" placeholder="全部"/>
                    </a-form-item>
                  </a-col>
                  <a-col flex="360px">
                    <a-input-group>
                      <a-select v-model="query.time_type" placeholder="时间类型" :style="{width:'120px'}">
                        <a-option value="created_at" label="添加时间" />
                        <a-option value="updated_at" label="修改时间" />
                      </a-select>
                      <a-range-picker v-model="query.date_value" allow-clear style="width: 100%"/>
                    </a-input-group>
                  </a-col>
                </a-row>
              </a-form>
            </a-col>
            <a-col flex="86px" style="text-align: right">
              <a-space :size="6">
                <a-button type="primary" @click="search">
                  <template #icon><icon-search /></template>搜索
                </a-button>
                <a-button @click="refresh()">
                  <template #icon><icon-refresh /></template>重置
                </a-button>
              </a-space>
            </a-col>
          </a-row>
        </div>
        <div class="table-content">
          <div class="table-header lg:flex justify-between mb-2">
            <a-space class="lg:flex block lg:inline-block">
              <a-space>
                <a-checkbox @change="customSelectAll">
                  <template #checkbox="{ checked }">
                    <a-space
                      align="start"
                      class="custom-checkbox-card"
                      :class="{ 'custom-checkbox-card-checked': checked }"
                    >
                      <div class="custom-checkbox-card-mask">
                        <div class="custom-checkbox-card-mask-dot" />
                      </div>
                      <div>
                        <div class="custom-checkbox-card-title">全选</div>
                      </div>
                    </a-space>
                  </template>
                </a-checkbox>
                <a-button type="primary" status="warning" size="small" @click="batchSelect('hide')">批量操作</a-button>
                <a-button type="primary" status="danger" size="small" @click="batchDel()">
                  <template #icon><icon-delete /></template>批量删除
                </a-button>
                <a-button status="warning" size="small" @click="doExport()">
                  <template #icon><icon-download /></template>下载
                </a-button>
                <a-button size="small" @click="doImport()">
                  <template #icon><icon-upload /></template>导入
                </a-button>
                <a-button type="primary" size="small" @click="add()">
                  <template #icon><icon-plus /></template>
                  <template #default>添加</template>
                </a-button>
                <a-button type="primary" size="small" @click="batchAdd()">批量添加</a-button>
              </a-space>
            </a-space>
            <a-space class="lg:mt-0 mt-2">
              <a-tooltip content="刷新表格"><a-button shape="circle" @click="refresh"><icon-refresh /></a-button></a-tooltip>
              <a-tooltip content="显隐搜索"><a-button shape="circle" @click="toggleSearch"><icon-search /></a-button></a-tooltip>
              <a-tooltip content="设置"><a-button shape="circle" @click="setTableColumns"><icon-settings /></a-button></a-tooltip>
            </a-space>
          </div>
          <div ref="tableContainerRef">
            <a-table
              ref="tableRef"
              row-key="id"
              :loading="loading"
              :pagination="false"
              :data="renderData"
              :bordered="{ wrapper: true, cell: true }"
              :row-selection="rowSelection"
              :scroll="tableScroll"
              column-resizable
              @select="select"
              @selection-change="selectionChange"
              @page-change="onPageChange"
              @page-size-change="onPageSizeChange"
              @sorter-change="sorting"
            >
              <template #columns>
                <vue-table-column :columns="columns">
                  <template #status="{ record }">
                    <span v-if="record.status === '1'" class="circle"></span>
                    <span v-else class="circle pass"></span>
                    状态名
                  </template>
                  <template #operations="{ record }">
                    <a-space>
                      <a-button type="primary" size="small" @click="add(record)"><template #icon><icon-edit /></template>编辑</a-button>
                      <a-popconfirm content="确定要删除这条数据吗？" type="warning" position="br" @ok="del([record])">
                        <a-button type="primary" status="danger" size="small"><template #icon><icon-delete /></template>删除</a-button>
                      </a-popconfirm>
                    </a-space>
                  </template>
                </vue-table-column>
              </template>
            </a-table>
          </div>
        </div>
        <div class="table-footer mt-3 text-right" v-if="pagination.total > 0">
          <pagination-manage
            v-show="pagination.total > 0"
            :total="pagination.total"
            :current="pagination.current"
            :page-size="pagination.pageSize"
            @pageCBK="onPageChange"
            @pageSizeCBK="onPageSizeChange"
          />
        </div>
      </a-card>
    </a-spin>

    <SetColumn ref="setColumnRef" :columns="columns" @update:columns="updateColumns"/>

    <Detail ref="detailRef" @saveCallback="fetchData"/>
    <BatchAdd ref="batchAddRef" @saveCallback="fetchData"/>
    <ImportData ref="importRef" @saveCallback="fetchData"/>
  </div>
</template>

<script setup>
  import { ref, reactive, h, compile, nextTick, computed, onMounted, onUnmounted } from 'vue';
  import { Message, Modal } from '@arco-design/web-vue';

  import useLoading from '@/hooks/loading';
  import { workAreaHeight, downloadFile } from '@/utils/index';
  import { apiList, apiDel, apiExport } from '@/api/test';
  import PaginationManage from '@/components/pagination/index.vue';
  import VueTableColumn from '@/components/table/table-column.vue';
  import SetColumn from '@/components/table/set-column.vue';
  import Detail from './components/detail.vue';
  import BatchAdd from './components/batch-add.vue';
  import ImportData from './components/import.vue';

  const { loading, setLoading } = useLoading(false);
  const baseQuery = () => {
    return {
      page: 1,
      limit: 20,
      keyword_type: 'name',
      name: '',
      type: '1', // 不能用数字
      time_type: 'created_at',
      date_value: [],
      status: '',
    };
  };
  const bodyCellStyle = (record) => {
    if (record.id % 2 === 0) {
      return {
        color: '#f53f3f',
        'font-weight': 'bold',
      };
    }
    if (record.id % 3 === 0) {
      return {
        color: '#ffb400',
        'font-weight': 'bold',
      };
    }
    return {};
  }
  const baseColumns = () => {
    return [
      {
        title: 'ID', dataIndex: 'id', width: 80,
        align: 'center', fixed: 'left',
        sortable: {sortDirections: ['ascend', 'descend']},
        bodyCellStyle: bodyCellStyle,
      },
      {
        title: '名称', dataIndex: 'name', width: 160,
        align: 'center',
        bodyCellStyle: bodyCellStyle,
      },
      {
        title: '详情', dataIndex: 'info', width: 220,
        align: 'center',
        hide: true,
      },
      {
        title: '创建时间', dataIndex: 'created_at', width: 180,
        align: 'center',
        sortable: {sortDirections: ['ascend', 'descend']},
      },
      {
        title: '状态', dataIndex: 'status', width: 80,
        align: 'center',
        slotName: 'status',
      },
      {
        title: '操作', dataIndex: 'operations', width: 180,
        align: 'center', fixed: 'right',
        slotName: 'operations',
      },
    ];
  };
  const columns = ref([]);
  const renderData = ref([]);
  const query = ref(baseQuery());
  const pagination = reactive({});
  const rowSelection = reactive({
    type: 'checkbox',
    selectedRowKeys: [],
    // defaultSelectedRowKeys: [],
    showCheckedAll: true,
  });
  const tableScroll = ref({
    x: '100%',
    y: '100%',
  });

  const searchRef = ref();
  const showSearch = ref(true);
  const tableContainerRef = ref();
  const tableRef = ref();
  const setColumnRef = ref();
  const searchHeight = ref(0);

  const isReset = ref(true); // 是否重置
  let selectionKeys = []; // 选中项ID
  let selectionDatas = []; // 选中项
  const spinLoading = ref(false);
  const spinTip = ref();
  const detailRef = ref();
  const batchAddRef = ref();
  const importRef = ref();

  const stateObj = {
    // dialogVisible: ref(false), // 无效
    // dialogTitle: '',
    // btnLoading: false,

    isSelectAll: false,
  };
  const statusOptions = computed(() => [
    {
      label: '状态一',
      value: 1,
    },
    {
      label: '状态二',
      value: 2,
    },
  ]);

  const settingFixedPage = () => {
    const workHeight = workAreaHeight(152);
    const tableHeight = workHeight - searchHeight.value;
    tableContainerRef.value.style.height = `${tableHeight}px`;
  };
  const resizeHandler = () => {
    searchHeight.value = searchRef.value.offsetHeight;
    settingFixedPage();
  };
  const toggleSearch = async () => {
    const dom = searchRef.value?.style;
    if (dom) {
      showSearch.value = !showSearch.value;
      await nextTick(() => {
        searchHeight.value = searchRef.value.offsetHeight;
        settingFixedPage();
      });
    }
  };
  const setTableColumns = () => {
    setColumnRef.value.init();
  };
  const updateColumns = (data) => {
    columns.value = data;
  };
  const initColumns = async () => {
    columns.value = baseColumns();
  };

  // 分页
  const onPageChange = async (page) => {
    isReset.value = false;
    await fetchData({ ...query.value, page });
  };
  const onPageSizeChange = async (limit) => {
    isReset.value = false;
    await fetchData({ ...query.value, limit });
  };
  // 列表
  const fetchData = async (
    params = { ...query.value }
  ) => {
    setLoading(true);
    await reset();
    try {
      const { data } = await apiList(params);
      renderData.value = data.data;
      query.value.page = params.page;
      query.value.limit = params.limit;
      pagination.current = params.page;
      pagination.pageSize = params.limit;
      pagination.total = data.total;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };
  // 添加/编辑
  const add = (row = {}) => {
    detailRef.value.fetchData(row);
  };
  // 删除
  const del = (row) => {
    if (!row.length) {
      selectMsg();
    } else {
      let title = '删除';
      let message = `确定要删除选中的 <span style="color:red">${row.length} </span> 条数据吗？`;
      let ids = row;
      if (row.length === 1 && row[0].id) {
        title = `${title}ID：${row[0].id}`;
        message = `确定要删除 <span style="color:red">${row[0].name} </span> 这条数据吗？`;
        ids = [row[0].id];
      }
      Modal.warning({
        title,
        content: () => h('div', { innerHTML: message }),
        closable: true,
        hideCancel: false,
        onOk: (async () => {
          setLoading(true);
          try {
            await apiDel({ids});
          } catch (err) {

          } finally {
            await fetchData({...query.value});
            setLoading(false);
          }
        }),
      });
    }
  };
  // 重置
  const reset = async () => {
    if (isReset.value) {
      rowSelection.selectedRowKeys = [];
      selectionKeys = [];
    } else {
      isReset.value = true;
    }
  };
  // 搜索
  const search = async () => {
    query.value.page = 1;
    await fetchData({...query.value});
  };
  // 刷新
  const refresh = async () => {
    query.value = baseQuery();
    await fetchData({...query.value});
  };
  // 排序
  const sorting = async (dataIndex, direction) => {
    query.value.sort_field = dataIndex;
    if (direction === 'ascend') {
      query.value.sort_value = 'asc';
      await fetchData({...query.value});
    }
    if (direction === 'descend') {
      query.value.sort_value = 'desc';
      await fetchData({...query.value});
    }
  };

  // 批量添加
  const batchAdd = () => {
    batchAddRef.value.initData();
  };
  // 导入
  const doImport = () => {
    importRef.value.initData();
  };

  // 点击行选择器时触发 -- table 表头 【废弃：全选时不触发】
  const select = (rowKeys, rowKey, record) => {
    selectionKeys = rowKeys;
    if (!rowKeys.includes(rowKey)) {
      selectionDatas.forEach((item, index) => {
        if (index === rowKey) {
          selectionDatas.splice(index, 1);
        }
      });
    } else {
      selectionDatas[rowKey] = record;
    }
  };
  // 已选择的数据行发生改变时触发 -- table 表头
  const selectionChange = (rowKeys) => {
    rowSelection.selectedRowKeys = rowKeys;
    selectionKeys = rowKeys;
    selectionDatas = [];
    renderData.value.forEach((record, index) => {
      const rowKey = record.id;
      if (rowKeys.includes(rowKey) && !selectionDatas[rowKey]) {
        selectionDatas[rowKey] = record;
      }
    });
  };
  // 全选操作 -- 自定义按钮
  const customSelectAll = (value) => {
    tableRef.value.selectAll(value);
  };
  const selectMsg = (message) => {
    Message.info(message || '请选择需要操作的数据');
  };
  // 批量选择
  const batchSelect = (selectType) => {
    console.log(selectionKeys);
    if (!selectionKeys.length) {
      selectMsg();
    } else {
      console.log(selectType);
    }
  };
  // 批量删除
  const batchDel = () => {
    del(selectionKeys);
  };

  // 导出
  const doExport = async () => {
    spinLoading.value = true;
    spinTip.value = '数据下载中，请稍候...';
    await apiExport({...query.value}).then(res => {
      spinLoading.value = false;
      const { url } = res.data;
      downloadFile(url);
    }).catch(() => {
      spinLoading.value = false;
    });
  };

  onMounted(async () => {
    await initColumns();
    await fetchData();
    window.addEventListener('resize', resizeHandler, false);
    searchHeight.value = searchRef.value.offsetHeight;
    settingFixedPage();
  });
  onUnmounted(() => {
    window.removeEventListener('resize', resizeHandler, false);
  });
</script>

<script>
  export default {
    name: 'Test',
  };
</script>

<style scoped lang="less">

</style>
